package sein.android.hopenote;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import sein.android.hopenote.Const.HopeNoteDb;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;


public class Note_Add  extends Activity{
	
	private DBAdapter HnopenHelper;
	private SQLiteDatabase sdb;
	private Button bt_save, bt_close;
	private EditText et_date, et_time;
	private TextView tv_group;
	private String str_group, qWhere;
	private Cursor cursor;
	private ListView lv_item;
	private ArrayList<ItemData> Item_arr;
	private Note_Add_Adapter I_adapter;
	private int iYear, iMonth, iDay, iHour, iMinute;
	static final int DATE_DIALOG_ID = 0, TIME_DIALOG_ID = 1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.note_add);
		
		IntentFilter filter = new IntentFilter("BR_NoteAdd");
		registerReceiver(BR_NoteAdd,filter);
		
		setTitle(HopeNoteDb.CURRENT_USER);
		
		HnopenHelper = new DBAdapter(this);
        sdb = HnopenHelper.getReadableDatabase();
        
    	bt_save = (Button)findViewById(R.id.bt_save);
    	bt_close = (Button)findViewById(R.id.bt_close);
        tv_group = (TextView)findViewById(R.id.tv_group);
        lv_item = (ListView)findViewById(R.id.lv_item); 
        str_group = HopeNoteDb.CURRENT_GROUP;
        et_date = (EditText)findViewById(R.id.et_date);
        et_time = (EditText)findViewById(R.id.et_time);
        
        DateTimeInit();
        
        
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
		Date date = new Date();
		et_date.setText(dateFormat.format(date));
		et_time.setText(timeFormat.format(date));
		
		
        tv_group.setText(str_group);
        
        
        qWhere = HopeNoteDb.COL_GROUP + " = '" + str_group + "'";
    	cursor = sdb.query(HopeNoteDb.TB_ITEM, new String[] {HopeNoteDb.COL_ITEM,HopeNoteDb.COL_CNT,HopeNoteDb.COL_UNIT}, qWhere, null, null, null, null);
    	
    	cursor.moveToFirst();
        Item_arr = new ArrayList<ItemData>();
        ItemData datarow;
        for(int i=0; i < cursor.getCount(); i++)
        {
        	datarow = new ItemData(cursor.getString(0),cursor.getString(1),cursor.getString(2),"","");
        	Log.i("cursor",cursor.getString(0)+","+cursor.getString(1)+","+cursor.getString(2) );
        	Item_arr.add(datarow);
        	cursor.moveToNext();
        }
        cursor.close();
        I_adapter = new Note_Add_Adapter(Note_Add.this, R.layout.note_add_row, Item_arr);
        lv_item.setAdapter(I_adapter);
        //lv_item.setItemsCanFocus(true);
        
        et_date.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(DATE_DIALOG_ID);
			}
		});
        
        et_time.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(TIME_DIALOG_ID);
			}
		});
        
        bt_save.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(v.getId() == R.id.bt_save )
				{
					if(HopeNoteDb.CURRENT_USER.equals(""))
					{
						Toast.makeText(Note_Add.this, "사용자를 선택하세요.", Toast.LENGTH_SHORT).show();
						return;
					}
					ContentValues row = new ContentValues();
					
					//기록 등록
					//SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					//Date date = new Date();
					String dt = et_date.getText().toString() + " " + et_time.getText().toString();
					
					try {
						int i = 0;
						for(; i < lv_item.getCount(); i++)
						{
							ItemData this_row = (ItemData)lv_item.getItemAtPosition(i);
							String item_name = this_row.item_name;
							String document1 = this_row.document1;
							String document2 = this_row.document2;

							if(!document1.equals("") || !document2.equals(""))
							{	
								//row.put(HopeNoteDb.COL_DATE, dateFormat.format(date));
								row.put(HopeNoteDb.COL_DATE, dt);
								row.put(HopeNoteDb.COL_USER, HopeNoteDb.CURRENT_USER);
								row.put(HopeNoteDb.COL_ITEM, item_name);
								row.put(HopeNoteDb.COL_DOCUMENT1, document1);
								row.put(HopeNoteDb.COL_DOCUMENT2, document2);
								
								sdb.insert(HopeNoteDb.TB_NOTE, null, row);
							}
							this_row.et_document1.setText("");
							this_row.et_document2.setText("");
						}
						if( i == 0 )
						{
							Toast.makeText(Note_Add.this, "기입한 기록이 없습니다.", Toast.LENGTH_SHORT).show();
							return;
						}
						Toast.makeText(Note_Add.this, "등록 완료", Toast.LENGTH_SHORT).show();
						Intent intent = new Intent("Reset");
						sendBroadcast(intent);
					} catch (Exception e) {
						// TODO: handle exception
						Toast.makeText(Note_Add.this, "등록 실패", Toast.LENGTH_SHORT).show();
					}
				}
			}
		});
        
        bt_close.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
	
	public void DateTimeInit()
	{
		final Calendar objTime = Calendar.getInstance();
        iYear = objTime.get(Calendar.YEAR);
        iMonth = objTime.get(Calendar.MONTH);
        iDay = objTime.get(Calendar.DAY_OF_MONTH);
        iHour = objTime.get(Calendar.HOUR_OF_DAY);
        iMinute = objTime.get(Calendar.MINUTE);
	}
	
	protected Dialog onCreateDialog(int id)
	{
		switch(id)
		{
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, iYear, iMonth, iDay);
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, iHour, iMinute, true);
		}
		return null;
	}
	
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			// TODO Auto-generated method stub
			String tMon, tDay;
			iYear = year;
			iMonth = monthOfYear;
			iDay = dayOfMonth;
			
			tMon = Integer.toString(iMonth+1);
			tDay = Integer.toString(iDay);
			if(tMon.length() == 1)
			{
				tMon = "0" + tMon;
			}
			if(tDay.length() == 1)
			{
				tDay = "0" + tDay;
			}
			updateDisplay(et_date, new StringBuilder().append(iYear).append("-").append(tMon).append("-").append(tDay));
		}
	};
	
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			String tHour, tMin;
			
			iHour = hourOfDay;
			iMinute = minute;
			
			tHour = Integer.toString(iHour);
			tMin = Integer.toString(iMinute);
			
			if(tHour.length() == 1)
			{
				tHour = "0" + tHour;
			}
			if(tMin.length() == 1)
			{
				tMin = "0" + tMin;
			}
			updateDisplay(et_time, new StringBuilder().append(tHour).append(":").append(tMin));
		}
	};
	
	private void updateDisplay(EditText et, StringBuilder str)
	{
		et.setText(str);
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.activity_main, menu);
		super.onCreateOptionsMenu(menu);
		menu.add(0,1,0,"사용자").setIcon(R.drawable.ic_action_search);
		menu.add(0,2,0,"항목관리").setIcon(R.drawable.ic_action_search);
		return true;		
    }

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		case 1:
			Intent list = new Intent(this, User_List.class);
			startActivity(list);
			return true;
			
		case 2:
			Intent item_input = new Intent(this, Item_Input.class);
			startActivity(item_input);
			return true;
		}
		return false;
	}
	
	private BroadcastReceiver BR_NoteAdd = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			setTitle(HopeNoteDb.CURRENT_USER);
		}
	};
}





